package com.qiahao.service.impl;

import com.qiahao.bean.User;
import com.qiahao.dto.ResponseData;
import com.qiahao.dto.UserDto;
import com.qiahao.jwt.JwtTokenUtil;
import com.qiahao.mapper.UserMapper;
import com.qiahao.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2018/4/2 0002.
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;
    private JwtTokenUtil jwtTokenUtil;
    private UserMapper userRepository;

    @Autowired
    public UserServiceImpl(AuthenticationManager authenticationManager, UserDetailsService userDetailsService, JwtTokenUtil jwtTokenUtil, UserMapper userRepository) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userRepository = userRepository;
    }

    @Override
    public ResponseData login(String username, String password) {
        ResponseData data = new ResponseData();
        Map<String, Object> map = new HashMap();
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, "111");
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        map.put("token", "token" + jwtTokenUtil.generateToken(userDetails));
        data.setData(map);
        data.setMsg("登录成功");
        return data;
    }

    @Override
    public ResponseData register(User user) {
        ResponseData data = new ResponseData();
        String username = user.getUsername();
        if (userRepository.findByUsername(username) != null) {
            data.setMsg("用户名称已存在");
            return data;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = user.getPassword();
        user.setPassword(encoder.encode(rawPassword));
        userRepository.addUser(user);
        data.setMsg("注册成功");
        return data;
    }

    @Override
    public String refreshToken(String oldToken) {
        String token = oldToken.substring("token ".length());
        if (!jwtTokenUtil.isTokenExpired(token)) {
            return jwtTokenUtil.refreshToken(token);
        }
        return "error";
    }

    @Override
    public ResponseData updateUser(User user) {


        return null;
    }

    @Override
    public ResponseData modifyPswd(User user, String newPassword) {
        ResponseData data = new ResponseData();

        String msg = "";

        Long userId = user.getId();

        if (userId == null) {
            msg = "用户id不能为空";
        }

        UserDto userInfo = userRepository.findByUserById(userId);

        if (userInfo == null) {
            msg = "用户不存在";
        }

        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = user.getPassword();

        if (!encoder.matches(rawPassword, userInfo.getPassword())) {
            msg = "原密码不正确";
        }

        if (!StringUtils.isEmpty(msg)) {
            data.setMsg(msg);
            return data;
        }
        user.setPassword(encoder.encode(newPassword));
        userRepository.updateUser(user);
        msg = "修改成功";
        data.setMsg(msg);
        return data;
    }

}
